"use client";
import React, { useState, useEffect } from "react";
import {
  Button,
  Skeleton,
  Alert,
  Pagination,
  Breadcrumb,
  Input,
  Tag,
  Modal,
  Spin,
  Empty,
  Select,
} from "antd";
import { useRouter } from "next/navigation";
import { createStyles } from "antd-style";
import {
  SearchOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
} from "@ant-design/icons";
import {
  standardStatistics,
  standardGetStandardPageH5,
  standardGetStandardDetailH5,
} from "@/apis";

// === types ===
interface StandardCategory {
  key: string;
  label: string;
  count?: number;
  value?: string;
}

interface H5StandardModel {
  id: number;
  category: string;
  communityName: string;
  standardNumber: string;
  standardName: string;
  publicationDate: string;
  status: string;
  draftingUnit: string;
  technicalContent: string;
  publishment: boolean;
  standardTextName: string;
  standardTextAddress: string;
}

interface ResponseDataListModel<T> {
  total: number;
  data: T[];
}

interface ResponseModel<T> {
  success?: boolean;
  code?: number;
  message?: string;
  data?: T;
}

interface H5StandardDetail extends H5StandardModel {}

// === 样式 ===
const useStyle = createStyles(({ prefixCls, css }) => ({
  categoryButtonGroup: css`
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-bottom: 20px;
  `,
  categoryButton: css`
    position: relative;
    border-radius: 4px;
    transition: all 0.3s ease;
    &.${prefixCls}-btn {
      background: #fff;
      color: #333;
      border: 1px solid #d9d9d9;
      &:hover:not([disabled]) {
        border-color: #2570ff;
        color: #2570ff;
        background: #f0f7ff;
      }
    }
  `,
  categoryButtonActive: css`
    &.${prefixCls}-btn {
      background: linear-gradient(135deg, #2570ff, #1890ff);
      color: #fff;
      border: none;
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
      &:hover:not([disabled]) {
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
        background: linear-gradient(135deg, #1890ff, #096dd9);
      }
    }
  `,
  searchContainer: css`
    width: 100%;
    margin: 30px 0;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
  `,
  searchInput: css`
    flex: 1;
    max-width: 600px;
  `,
  standardCard: css`
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 16px;
    transition: all 0.3s ease;
    cursor: pointer;
    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      transform: translateY(-2px);
    }
  `,
  cardHeader: css`
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px dashed #e0e0e0;
  `,
  standardTitle: css`
    font-size: 16px;
    font-weight: bold;
    color: #2f2f2f;
    margin-bottom: 4px;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  `,
  standardMeta: css`
    display: flex;
    flex-wrap: wrap;
    gap: 8px 16px;
    font-size: 14px;
    color: #666;
    margin-bottom: 12px;
  `,
  metaItem: css`
    display: flex;
    align-items: center;
    &::before {
      content: "•";
      font-size: 8px;
      margin-right: 4px;
      color: #999;
    }
  `,
  technicalContent: css`
    font-size: 14px;
    color: #333;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    margin-bottom: 12px;
    padding: 8px;
    background-color: #f9f9f9;
    border-radius: 4px;
  `,
  cardFooter: css`
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 13px;
  `,
  statusBadge: css`
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
  `,
  infoTag: css`
    margin-left: 8px;
    font-size: 12px;
  `,
  modalContent: css`
    max-height: 70vh;
    overflow-y: auto;
  `,
  // 公开标准卡片背景
  publicCard: css`
    background-color: #f6ffed !important;
    border: 1px solid #b7eb8f !important;
  `,
  // 未公开标准卡片背景
  privateCard: css`
    background-color: #fff1f0 !important;
    border: 1px solid #ffccc7 !important;
  `,
  // 新增标题容器样式
  standardTitleContainer: css`
    display: flex;
    align-items: center;
    margin-bottom: 4px;
  `,

  // 修改标题文本样式
  standardTitleText: css`
    font-size: 16px;
    font-weight: bold;
    color: #2f2f2f;
    flex: 1;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  `,
  // 公开标签样式
  publicTag: css`
    background-color: #f6ffed;
    border-color: #b7eb8f;
    color: #52c41a;
  `,
  // 未公开标签样式
  privateTag: css`
    background-color: #fff1f0;
    border-color: #ffccc7;
    color: #ff4d4f;
  `,
}));

export default function StandardList() {
  const highlightKeyword = (text: string, keyword: string) => {
    if (!keyword.trim()) return text;

    const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    const regex = new RegExp(`(${escapedKeyword})`, "gi");

    return text.replace(
      regex,
      '<span style="color: blue; font-weight: bold;font-size:24px;">$1</span>'
    );
  };
  const { styles } = useStyle();
  const router = useRouter();

  const [categories, setCategories] = useState<StandardCategory[]>([]);
  const [currentCategory, setCurrentCategory] = useState("全部");
  const [selectedCategoryValue, setSelectedCategoryValue] = useState<
    string | null
  >(null);
  const [totalStandardCount, setTotalStandardCount] = useState(0);
  const [categoryLoading, setCategoryLoading] = useState(false);
  const [categoryError, setCategoryError] = useState<string | null>(null);

  const [standardList, setStandardList] = useState<H5StandardModel[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(30);
  const [totalItems, setTotalItems] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState("");
  const [publishmentFilter, setPublishmentFilter] = useState<string | null>(
    null
  );
  const [standardLoading, setStandardLoading] = useState(false);
  const [standardError, setStandardError] = useState<string | null>(null);

  // === Modal 状态 ===
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedStandardDetail, setSelectedStandardDetail] =
    useState<H5StandardDetail | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  // 获取分类
  const fetchCategories = async () => {
    setCategoryLoading(true);
    setCategoryError(null);
    try {
      const response = await standardStatistics<false>({
        baseURL: "/api/proxy",
      });
      const businessData = response.data;
      if (businessData?.success && Array.isArray(businessData.data)) {
        const formattedCategories = businessData.data.map((item: any) => ({
          key: item.category,
          label: item.category,
          count: item.num,
          value: item.category,
        }));
        setCategories(formattedCategories);
        const total = formattedCategories.reduce(
          (sum, item) => sum + (item.count || 0),
          0
        );
        setTotalStandardCount(total);
      } else setCategoryError("获取分类失败");
    } catch (err) {
      console.error(err);
      setCategoryError("网络异常，无法加载分类");
    } finally {
      setCategoryLoading(false);
    }
  };

  // 获取标准列表
  // 1. 新增状态存储“其他”分类的数量
  const [otherCategoryCount, setOtherCategoryCount] = useState(0);

  // 2. 修改 fetchStandards，新增统计“其他”分类数量的逻辑
  const fetchStandards = async (isCountOther = false) => {
    setStandardLoading(true);
    setStandardError(null);

    try {
      const condition: Record<string, any> = {
        page: 1, // 只需要第1页数据的total，无需加载全部
        size: 1,
        category: "其他", // 只筛选“其他”分类
      };
      // 构建查询参数（同原有逻辑）
      const queryObj: Record<string, string> = {};
      Object.entries(condition).forEach(([k, v]) => {
        if (v !== undefined && v !== "") queryObj[`condition.${k}`] = String(v);
      });
      const queryString = new URLSearchParams(queryObj).toString();

      // 请求“其他”分类的数量
      const response = await standardGetStandardPageH5<false>({
        baseURL: "/api/proxy",
        url: `/standard/h5?${queryString}`,
      });
      const result = response.data as ResponseModel<
        ResponseDataListModel<H5StandardModel>
      >;
      if (result.success && isCountOther) {
        // 存储“其他”分类的真实数量
        setOtherCategoryCount(result.data?.total || 0);
      }

      // ----------------------
      // 以下是原有“标准列表筛选”逻辑
      // ----------------------
      const normalCondition: Record<string, any> = {
        keyword: searchKeyword.trim() || undefined,
        page: currentPage,
        size: pageSize,
      };
      if (selectedCategoryValue && selectedCategoryValue !== "全部") {
        normalCondition.category = selectedCategoryValue;
      }
      // 注意：API不支持publishment筛选，将在前端进行筛选
      const normalQueryObj: Record<string, string> = {};
      Object.entries(normalCondition).forEach(([k, v]) => {
        if (v !== undefined && v !== "" && v !== null)
          normalQueryObj[`condition.${k}`] = String(v);
      });
      const normalQueryString = new URLSearchParams(normalQueryObj).toString();
      const normalResponse = await standardGetStandardPageH5<false>({
        baseURL: "/api/proxy",
        url: `/standard/h5?${normalQueryString}`,
      });
      const normalResult = normalResponse.data as ResponseModel<
        ResponseDataListModel<H5StandardModel>
      >;
      if (normalResult.success) {
        let filteredData = normalResult.data?.data || [];

        // 前端筛选：按公开状态筛选
        if (publishmentFilter !== null) {
          const isPublic = publishmentFilter === "true";
          filteredData = filteredData.filter(
            (item) => item.publishment === isPublic
          );
        }

        setStandardList(filteredData);
        setTotalItems(filteredData.length);
      } else {
        setStandardList([]);
        setTotalItems(0);
        setStandardError(normalResult.message || "获取标准数据失败");
      }
    } catch (err) {
      console.error(err);
      setStandardError("网络异常，无法加载标准数据");
    } finally {
      setStandardLoading(false);
    }
  };

  // 3. 首次加载时，统计“其他”分类的数量
  useEffect(() => {
    if (!categoryLoading && !categoryError) {
      fetchStandards(true); // 传入isCountOther=true，触发统计
    }
  }, [categoryLoading, categoryError]);

  useEffect(() => {
    fetchCategories();
  }, []);
  useEffect(() => {
    if (!categoryLoading && !categoryError) fetchStandards();
  }, [
    selectedCategoryValue,
    currentPage,
    searchKeyword,
    publishmentFilter,
    categoryLoading,
    categoryError,
  ]);

  // 分类点击
  const handleCategoryClick = (key: string) => {
    if (currentCategory === key) return;
    setCurrentCategory(key);
    setCurrentPage(1);
    setSelectedCategoryValue(key === "全部" ? null : key);
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };
  const handleSearch = () => {
    setCurrentPage(1);
    fetchStandards();
  };

  const handlePublishmentFilterChange = (value: string | null) => {
    setPublishmentFilter(value);
    setCurrentPage(1);
  };
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") handleSearch();
  };

  // 打开详情 Modal
  const openDetailModal = async (id: number) => {
    setDetailModalVisible(true);
    setDetailLoading(true);
    try {
      const res = await standardGetStandardDetailH5({
        baseURL: "/api/proxy",
        url: `/standard/h5/detail?id=${id}`,
      });
      if (res.data?.success) {
        setSelectedStandardDetail(res.data.data);
      } else {
        setSelectedStandardDetail(null);
      }
    } catch (err) {
      console.error(err);
      setSelectedStandardDetail(null);
    } finally {
      setDetailLoading(false);
    }
  };

  const getCategoryButtons = () => {
    const knownTotal = categories.reduce(
      (sum, item) => sum + (item.count || 0),
      0
    );
    // 关键修改：用真实的“其他”分类数量（otherCategoryCount）替换原计算逻辑
    const otherCount = otherCategoryCount;
    // 重新计算总数量（已知分类 + 其他分类）
    const realTotalStandardCount = knownTotal + otherCount;

    const baseCats = [
      // 总数量改为“已知分类 + 其他分类”
      {
        key: "全部",
        label: `全部 (${realTotalStandardCount.toLocaleString()})`,
      },
      ...categories.map((c) => ({
        key: c.key,
        label: `${c.label} (${c.count?.toLocaleString() || 0})`,
      })),
    ];
    // “其他”分类显示真实数量
    const otherCat = {
      key: "其他",
      label: `其他 (${otherCount.toLocaleString()})`,
    };
    return [...baseCats, otherCat];
  };

  const getBreadcrumbItems = () => {
    const displayCategory =
      currentCategory === "其他" ? "其他" : currentCategory;
    return [
      {
        title: (
          <span onClick={() => router.push("/")} className="cursor-pointer">
            首页
          </span>
        ),
        key: "home",
      },
      {
        title: (
          <span
            onClick={() => router.push("/standards")}
            className="cursor-pointer"
          >
            标准检索列表
          </span>
        ),
        key: "standards",
      },
      {
        title: displayCategory,
        key: `category-${currentCategory}`,
        isCurrent: true,
      },
    ];
  };

  const getStatusStyle = (status: string) => {
    switch (status) {
      case "现行":
      case "已发布":
        return { backgroundColor: "#e6f7ee", color: "#00875a" };
      case "起草中":
        return { backgroundColor: "#fffbe6", color: "#d48806" };
      case "已废止":
        return { backgroundColor: "#fff2f0", color: "#cf1322" };
      default:
        return { backgroundColor: "#f0f2f5", color: "#4e5969" };
    }
  };

  const renderStandardCard = (s: H5StandardModel) => (
    <div
      key={s.id}
      className={`${styles.standardCard} ${
        s.publishment ? styles.publicCard : styles.privateCard
      }`}
      onClick={() => openDetailModal(s.id)}
    >
      <div className={styles.cardHeader}>
        {/* 修复：将标题和标签放在同一个容器中，避免冲突 */}
        <div className={styles.standardTitleContainer}>
          <span
            className={styles.standardTitleText}
            dangerouslySetInnerHTML={{
              __html: highlightKeyword(s.standardName, searchKeyword),
            }}
          />
          <Tag
            icon={s.publishment ? <EyeOutlined /> : <EyeInvisibleOutlined />}
            color={s.publishment ? "green" : "orange"}
            className={styles.infoTag}
          >
            {s.publishment ? "公开" : "未公开"}
          </Tag>
        </div>
        <div className={styles.standardMeta}>
          <div className={styles.metaItem}>
            编号: {s.standardNumber || "无编号"}
          </div>
          <div className={styles.metaItem}>分类: {s.category || "未分类"}</div>
          <div className={styles.metaItem}>
            发布机构: {s.communityName || "未知"}
          </div>
        </div>
      </div>
      <div className={styles.cardFooter}>
        <div>发布日期: {s.publicationDate || "未知"}</div>
        <div style={getStatusStyle(s.status || "未知")}>
          {s.status || "未知"}
        </div>
      </div>
    </div>
  );

  const renderStandards = () => {
    if (standardLoading)
      return Array(pageSize)
        .fill(0)
        .map((_, idx) => <Skeleton active key={idx} paragraph={{ rows: 4 }} />);
    if (standardError)
      return <Alert message={standardError} type="error" showIcon />;
    if (standardList.length === 0) return <Empty description="暂无相关标准" />;
    return standardList.map(renderStandardCard);
  };

  return (
    <section>
      <div className="container mx-auto mt-4 px-4">
        <Breadcrumb
          items={getBreadcrumbItems()}
          separator=">"
          className="mb-4"
        />
        <div className={styles.searchContainer}>
          <Input
            className={styles.searchInput}
            placeholder="请输入标准名称、编号或关键词搜索"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onPressEnter={handleSearch}
            prefix={<SearchOutlined />}
            // 添加清除功能
            allowClear
            // 清除按钮点击事件（可选，用于触发搜索）
            onClear={() => {
              setSearchKeyword("");
              setCurrentPage(1);
              fetchStandards(); // 清除后自动搜索
            }}
          />
          <Select
            placeholder="公开状态"
            value={publishmentFilter}
            onChange={handlePublishmentFilterChange}
            allowClear
            style={{ minWidth: 120 }}
            options={[
              { value: "true", label: "公开" },
              { value: "false", label: "未公开" },
            ]}
          />
          <Button
            type="primary"
            onClick={handleSearch}
            icon={<SearchOutlined />}
          >
            搜索
          </Button>
        </div>
        <div className={styles.categoryButtonGroup}>
          {categoryLoading ? (
            <Skeleton active paragraph={{ rows: 1, width: 200 }} />
          ) : categoryError ? (
            <Alert message={categoryError} type="error" showIcon />
          ) : (
            getCategoryButtons().map((btn) => (
              <Button
                key={btn.key}
                onClick={() => handleCategoryClick(btn.key)}
                className={`${styles.categoryButton} ${
                  currentCategory === btn.key ? styles.categoryButtonActive : ""
                }`}
                disabled={standardLoading}
              >
                {btn.label}
              </Button>
            ))
          )}
        </div>

        <div className="w-full grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {renderStandards()}
        </div>

        {!standardLoading && !standardError && totalItems > 0 && (
          <div className="w-full flex justify-center mt-8 mb-4">
            <Pagination
              current={currentPage}
              pageSize={pageSize}
              total={totalItems}
              onChange={handlePageChange}
              showSizeChanger={false}
              showQuickJumper
              showTotal={(total) => `共 ${total.toLocaleString()} 条`}
              defaultPageSize={30}
              defaultCurrent={1}
            />
          </div>
        )}
      </div>

      {/* === Modal 弹框 === */}
      <Modal
        open={detailModalVisible}
        // 关键修改：模态框标题高亮关键词
        title={
          <span
            dangerouslySetInnerHTML={{
              __html: highlightKeyword(
                selectedStandardDetail?.standardName || "标准详情",
                searchKeyword
              ),
            }}
          />
        }
        width={800}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
        ]}
      >
        <Spin spinning={detailLoading} tip="加载中...">
          {selectedStandardDetail ? (
            <div className={styles.modalContent}>
              <div className="mb-4">
                <Tag
                  icon={
                    selectedStandardDetail.publishment ? (
                      <EyeOutlined />
                    ) : (
                      <EyeInvisibleOutlined />
                    )
                  }
                  color={
                    selectedStandardDetail.publishment ? "green" : "orange"
                  }
                  className={
                    selectedStandardDetail.publishment
                      ? styles.publicTag
                      : styles.privateTag
                  }
                >
                  {selectedStandardDetail.publishment ? "公开" : "未公开"}
                </Tag>
              </div>
              <div className="mb-4 leading-10">
                <p>编号: {selectedStandardDetail.standardNumber || "无编号"}</p>
                <p>分类: {selectedStandardDetail.category || "未分类"}</p>
                <p>
                  发布机构: {selectedStandardDetail.communityName || "未知"}
                </p>
                <p>
                  起草单位:
                  <span className="text-[#666]">
                    {selectedStandardDetail.draftingUnit || "未知"}
                  </span>
                </p>
                <p>
                  发布日期: {selectedStandardDetail.publicationDate || "未知"}
                </p>
                <p>
                  状态:{" "}
                  <span
                    className={styles.statusBadge}
                    style={getStatusStyle(
                      selectedStandardDetail.status || "未知"
                    )}
                  >
                    {selectedStandardDetail.status || "未知"}
                  </span>
                </p>
              </div>
              <div
                className="mb-4 p-4 bg-gray-50 rounded"
                dangerouslySetInnerHTML={{
                  __html: highlightKeyword(
                    selectedStandardDetail.technicalContent ||
                      "暂无技术内容描述",
                    searchKeyword
                  ),
                }}
              />
              {selectedStandardDetail.standardTextName &&
                selectedStandardDetail.standardTextAddress && (
                  <div>
                    <a
                      href={selectedStandardDetail.standardTextAddress}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      下载附件: {selectedStandardDetail.standardTextName}
                    </a>
                  </div>
                )}
            </div>
          ) : (
            <Alert message="获取详情失败" type="error" />
          )}
        </Spin>
      </Modal>
    </section>
  );
}
